<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\PointsProduct;
use App\Models\Search;
use App\Http\Controllers\Api\V1\Resources\PointsProductResource;
use App\Http\Controllers\Api\V1\Resources\ActivityItemResource;
use App\Services\MakeCouponsUsePoints\MakeCouponsUsePointRequest;
use App\Services\MakeCouponsUsePoints\MakeCouponsUsePoint;
use Illuminate\Support\Facades\Cache;

class PointsProductsController extends Controller
{
    
   

    public function index()
    {
        $keyword = request('keyword');
        PointsProductResource::wrap('data');

        $query = PointsProduct::query();

        
        if($keyword){
            $query = $query->where('title', 'like', "%{$keyword}%");
        }

         $pointsProduct = $query->orderByDesc('id')->paginate();
        
       
        return PointsProductResource::collection($pointsProduct);
    }

    public function show($id)
    {

      $pointsProduct = PointsProduct::find($id);
      return new  PointsProductResource($pointsProduct);
    }

    public function store()
    {
      $lock = Cache::lock('point_to_coupons', 15);

        try {

            if (! $lock->get()) fail('高峰拥挤，请再试');

            $request = app(MakeCouponsUsePointRequest::class);
            

            $record = app(MakeCouponsUsePoint::class, [
                'user' => $request->user(),
                'coupon_id' => $request->coupon_id,
                'point_product_id' => $request->point_product_id,
            ])->make();

           return response()->json(['record' => $record->toArray()]);

        } finally {
            $lock->release();
        }
    }
}
